use crate::config::{AUTH_URL, BASE_API_URL, CLIENTID};
use crate::errors::MyResult;
use crate::utils::{helper::redirect_to, response::ResponseHelper, url::get_query_param};
//use gloo::console::log;
use gloo_net::http::{Request, Response};
use serde::de::DeserializeOwned;
use serde::Serialize;

pub async fn post<T: Serialize, R: DeserializeOwned>(url: &str, data: T) -> MyResult<R> {
    let request_builder = Request::post(&format!("{}/{}", BASE_API_URL, url));
    let response = request_builder
        .header("token", &get_query_param("access_code").unwrap_or_default())
        .json(&data)?
        .send()
        .await?;

    if response.is_not_authed() {
        redirect_to(&format!("{}?client_id={}", AUTH_URL, CLIENTID));
    }
    let result = response.json::<R>().await?;
    Ok(result)
}

pub async fn get_with_param<'a, T, R: DeserializeOwned, V>(url: &str, param: T) -> MyResult<R>
where
    T: IntoIterator<Item = (&'a str, V)>,
    V: AsRef<str>,
{
    let request_builder = Request::get(&format!("{}/{}", BASE_API_URL, url));
    let response = request_builder
        .header("token", &get_query_param("access_code").unwrap_or_default())
        .query(param)
        .send()
        .await?;

    if response.is_not_authed() {
        redirect_to(&format!("{}?client_id={}", AUTH_URL, CLIENTID));
    }
    let result = response.json::<R>().await?;
    Ok(result)
}
pub async fn get<R: DeserializeOwned>(url: &str) -> MyResult<R> {
    let request_builder = Request::get(&format!("{}/{}", BASE_API_URL, url));
    let response: Response = request_builder
        .header("token", &get_query_param("access_code").unwrap_or_default())
        .send()
        .await?;

    if response.is_not_authed() {
        redirect_to(&format!("{}?client_id={}", AUTH_URL, CLIENTID));
    }
    let result = response.json::<R>().await?;
    Ok(result)
}
pub async fn delete<'a, T, V>(url: &str, param: T) -> MyResult<()>
where
    T: IntoIterator<Item = (&'a str, V)>,
    V: AsRef<str>,
{
    let request_builder = Request::delete(&format!("{}/{}", BASE_API_URL, url));
    let response = request_builder
        .header("token", &get_query_param("access_code").unwrap_or_default())
        .query(param)
        .send()
        .await?;

    if response.is_not_authed() {
        redirect_to(&format!("{}?client_id={}", AUTH_URL, CLIENTID));
    }
    Ok(())
}
